/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAEventViewController.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/22/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAEventViewController.h"
#import "InfoGalleriImageUrlUtils.h"
#import "LazyLoadManager.h"
#import "WebTextLength.h"
#import "BALibrarySettings.h"
#import "UIColor+HTML.h"
#import "BAWebBrowserViewController.h"
#import "BANewsRelatedsButtonViewController.h"

@interface BAEventViewController (){
    CGFloat imageHeight;
    CGFloat maxImageHeight;
    BANewsRelatedsButtonViewController* relatedMaterialsButtonViewController;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *headlineLabel;
@property (weak, nonatomic) IBOutlet UIWebView *bodyWebView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;

@property (weak, nonatomic) IBOutlet UILabel *monthLabel;
@property (weak, nonatomic) IBOutlet UILabel *dayLabel;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *entryLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;

@property (weak, nonatomic) IBOutlet UIView *locationView;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToBottomOfImageConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bodyWebViewHeight;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *timeLabelToHlineSpacing;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeightConstraint;



@end

@implementation BAEventViewController

+(BAEventViewController *)eventViewControlerWithNews:(BAEvent *)event{
    BAEventViewController* eventViewController;
    if (RD_IS_IPAD) {
        eventViewController = [[BAEventViewController alloc] initWithNibName:@"BAEventViewController_iPad" bundle:nil];
    } else{
        eventViewController = [[BAEventViewController alloc] initWithNibName:@"BAEventViewController_iPhone" bundle:nil];
    }
    [eventViewController setEvent:event];
    return eventViewController;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    BA_LABEL_SET_FONT_MEDIUM(self.headlineLabel);
//    BA_LABEL_SET_FONT_REGULAR(self.bodyLabel);
    BA_LABEL_SET_FONT_LIGHT(self.dayLabel);
    BA_LABEL_SET_FONT_MEDIUM(self.monthLabel);
    
    BA_LABEL_SET_FONT_REGULAR(self.timeLabel);
    BA_LABEL_SET_FONT_REGULAR(self.entryLabel);
    BA_LABEL_SET_FONT_BOLD(self.priceLabel);
    BA_LABEL_SET_FONT_MEDIUM(self.locationLabel);
    
    imageHeight = self.topToBottomOfImageConstraint.constant;
    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    
    relatedMaterialsButtonViewController = [BANewsRelatedsButtonViewController new];
    [self.bottomView addSubview:relatedMaterialsButtonViewController.view];
    [BAUtils setViewToFillParent:relatedMaterialsButtonViewController.view];
    [self addChildViewController:relatedMaterialsButtonViewController];

    [self.bodyWebView setBackgroundColor:[UIColor clearColor]];
    //id scrollView = [self.bodyWebView.subviews objectAtIndex:0];
    for (UIView * subview in [self.bodyWebView.scrollView subviews]) {
        if([subview isKindOfClass:[UIImageView class]])
            subview.hidden = YES;
    }
    [self.bodyWebView.scrollView setScrollEnabled:NO];
    
    self.scrollView.alwaysBounceVertical = YES;
    
    [self setupView];
}

-(void)dealloc{
    [[LazyLoadManager instance] cancelConnectionsForOwner:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setupView{
    self.bottomViewHeightConstraint.constant = 0;
    if (self.isViewLoaded && self.event != nil) {
        [self.headlineLabel setText:self.event.headline];
        
        relatedMaterialsButtonViewController.relatedMaterials = _event.relatedResources;

        NSString* bodytemplate = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BANewsEventsBodyTemplate" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
        if (bodytemplate==nil) {
            return;
        }
        NSMutableString* bodyHtml = [bodytemplate mutableCopy];// = [[NSString stringWithFormat:bodytemplate, [[[BALibrarySettings instance] getCustomerColorNormal] toHTMLColorString]] mutableCopy];
        [bodyHtml replaceOccurrencesOfString:@"%1$@"
                                  withString:[[[BALibrarySettings instance] getCustomerColorNormal] toHTMLColorString]
                                     options:0
                                       range:NSMakeRange(0, [bodyHtml length])];
        
        if ([self.event.subHeadline length]>0) {
            [bodyHtml appendFormat:@"<p><em>%@</em></p>",self.event.subHeadline];
        }
        
        [bodyHtml appendString:self.event.body];
        [bodyHtml appendString:@"<br /><div id=\"end\"></div></body></html>"];
        
        [self.bodyWebView loadHTMLString:bodyHtml baseURL:nil];
        
//        NSMutableAttributedString* body =[NSMutableAttributedString new];
//        [body appendAttributedString:[NSAttributedString attributedStringWithHTML:self.event.body]];
//        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
//        [style setLineSpacing:5];
//        [body addAttribute:NSParagraphStyleAttributeName
//                     value:style
//                     range:NSMakeRange(0, [body length])];
//        [self.bodyLabel setAttributedText:body];
        
        
        NSDate *startTime = [NSDate dateWithTimeIntervalSince1970:self.event.startTime];
        NSDate *endTime = [NSDate dateWithTimeIntervalSince1970:self.event.endTime];
        
        NSDateFormatter *dateFormatter = [NSDateFormatter new];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"da_DK"]];
        if (self.monthLabel != nil) {
            [dateFormatter setDateFormat:@"MMM"];
            [self.monthLabel setText:[[dateFormatter stringFromDate:startTime] uppercaseString]];
        }
        if (self.dayLabel != nil) {
            [dateFormatter setDateFormat:@"d"];
            [self.dayLabel setText:[dateFormatter stringFromDate:startTime]];
        }
        
        if (self.timeLabel) {
            [dateFormatter setDateFormat:@"HH:mm"];
            if (self.event.startTime == self.event.endTime) {
                [self.timeLabel setText:[NSString stringWithFormat:@"Kl. %@", [dateFormatter stringFromDate:startTime]]];
            } else {
                [self.timeLabel setText:[NSString stringWithFormat:@"Kl. %@ - %@", [dateFormatter stringFromDate:startTime], [dateFormatter stringFromDate:endTime]]];
            }
        }
        
        
        if (self.event.price.length == 0) {
            [self.priceLabel setHidden:YES];
            [self.entryLabel setHidden:YES];
            self.timeLabelToHlineSpacing.constant = 20;
        }
        
        if ([self.event.price isEqualToString:@"0"]) {
            [self.priceLabel setText:@"Gratis"];
        } else{
            [self.priceLabel setText:self.event.price];
        }
        
        if (self.event.location.length == 0) {
            [self.locationView setHidden:YES];
        }
        [self.locationLabel setText:self.event.location];
        
        
        NSString* resizeUrl;
        if (RD_IS_IPAD) {
            resizeUrl = [InfoGalleriImageUrlUtils getResizedImageUrl:self.event.imageUrl toWidth:683 toHeight:2000 usingQuality:7 withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX outputFormat:@"jpeg" doubleUpForRetina:YES]; // ?
        } else{
            resizeUrl = [InfoGalleriImageUrlUtils getResizedImageUrl:self.event.imageUrl toWidth:320 toHeight:1000 usingQuality:7 withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX outputFormat:@"jpeg" doubleUpForRetina:YES];
        }
        
        [[LazyLoadManager instance] lazyLoadUIImageFromUrl:resizeUrl withOwner:self setScaleforRetina:YES onSuccess:^(UIImage *image) {
            [self.imageView setImage:[UIImage imageWithCGImage:image.CGImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            [UIView animateWithDuration:0.25 animations:^{
                [self.imageView setAlpha:1];
            } completion:^(BOOL finished) {
                [self.loadingIndicator stopAnimating];
            }];
        } onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
            [self.loadingIndicator stopAnimating];
        }];
        
        if ([self.event.relatedResources count]>0) {
            self.bottomViewHeightConstraint.constant = 46;
            
        }
    }
}

-(void)setEvent:(BAEvent *)event{
    if (_event != event) {
        _event = event;

        /* test
        _event.subHeadline = @"Lorem ipsum dolor sit amelgamium. Underoverskriften skal vel vises under den vandrette streg, men med et andet skriftsnit end brødteksten?";
         */
        [self setupView];
    }
}


#pragma mark UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset = scrollView.contentOffset.y;
    
    self.topToBottomOfImageConstraint.constant = imageHeight-yOffset;
    
}
#pragma mark UIWebViewDelegate


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    if (webView == self.bodyWebView) {
        self.bodyWebViewHeight.constant = [WebTextLength measureWebBoxHeight:webView forMarker:@"end"];
    }
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [webView setAlpha:1];
    } completion:nil];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if (navigationType == UIWebViewNavigationTypeOther) {
        return YES;
    } else {
        NSString* absoluteRequestString = [request.URL absoluteString];
        if ([absoluteRequestString hasPrefix:@"http://"] || [absoluteRequestString hasPrefix:@"https://"]) {
            BAWebBrowserViewController* webBrowserViewControler = [[BAWebBrowserViewController alloc] initWithNibName:@"BAWebBrowserViewController" bundle:nil];
            [webBrowserViewControler setUrl:absoluteRequestString];
            [self presentViewController:webBrowserViewControler animated:YES completion:nil];
            
        } else if ([absoluteRequestString hasPrefix:@"mailto:"]) {
            [[UIApplication sharedApplication] openURL:request.URL];
        }
        return NO;
    }
}

@end
